from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import ClassMessage
import random
from .forms import MessageForm

# Create your views here.

def index(request):
	all_message = ClassMessage.objects.all()
	context = {'all_message': all_message}
	return render(request, 'message/index.html', context=context)

def look(request, message_id):
	message = get_object_or_404(ClassMessage, id=message_id)
	context = {'message': message}
	return render(request, 'message/look.html', context=context)

def randoms(request):
	all_message = ClassMessage.objects.all()
	count = ClassMessage.objects.all().count() - 1
	now_id = random.randint(0, count)
	message = ClassMessage.objects.all()[now_id]
	return HttpResponseRedirect(reverse('message:look', kwargs={'message_id': message.id}))

def editor(request):
	if request.method == 'POST':
		if request.user.classmessage == None:
			message = ClassMessage()
			message.message = request.POST['message']
			message.user = request.user
			message.save()
			return HttpResponseRedirect(reverse('message:look', kwargs={'message_id': message.id}))
		else:
			message = request.user.classmessage
			message.message = request.POST['message']
			message.save()
			return HttpResponseRedirect(reverse('message:look', kwargs={'message_id': message.id}))
	else:
		message_form = MessageForm()
		try:
			if request.user.classmessage == None:
				message_form.fields['message'].initial = 'None'
				return render(request, 'message/editor.html', context={'message_form': message_form})
			else:
				class_message = request.user.classmessage
				message_form.fields['message'].initial = class_message.message
				return render(request, 'message/editor.html', context={'message_form': message_form})
		except:
			class_message = ClassMessage()
			class_message.message = 'None'
			class_message.user = request.user
			class_message.save()
			message_form.fields['message'].initial = 'None'
			return render(request, 'message/editor.html', context={'message_form': message_form})
					
